<?php

/**
 * 根据分类获取列表
 * @param  integer
 * @param  integer
 * @param  integer
 * @return [type]
 */
function user_model_get_list($category_id = 0, $page = 1, $page_size = 8, $keywords = '') {
	//数据安全过滤
	//分类
	$category_id = intval($category_id);
	//分页
	$page = intval($page);
	if ($page <= 0) {
		$page = 1;
	}
	//页码转换成数据库limit
	$limit = ($page - 1) * $page_size;

	require_once APP_PATH . DIRECTORY_SEPARATOR . 'category/model.php';
	//获取下级所有分类ID
	$category_child_ids = category_model_get_child_ids($category_id);
	$category_ids = "";
	//分类ID通过,链接
	if (empty($category_child_ids)) {
		$category_ids = $category_id;
	} else {
		$category_ids = $category_child_ids . ',' . $category_id;
	}

	// 引入数据库链接操作
	require_once CORE_PATH . 'db.php';
	//sql查询
	$sql = "select * from users where category_id in(" . $category_ids . ") and`status` = 1 and `draft` =0    order by id desc limit " . $limit . "," . $page_size;
	//结果数组
	$users_array = array();
	try
	{
		//创建实力
		$db = Db::getInstance()->connect();
		//查询
		$result = mysqli_query($db, $sql);
		//结果处理
		if ($result) {
			//循环结果
			while ($row = mysqli_fetch_assoc($result)) {
				//加入结果
				$users_array[] = $row;
			}
		} else {
			//SQL报错停止
			die('mysql error' . mysqli_error($db));
		}

	} catch (Exception $e) {
		// 其他异常显示
	}
	//返回数组
	return $users_array;
}

function user_model_get_list_count($keywords = '') {
	//数据安全过滤
	//分类
	$category_id = intval($category_id);
	require_once APP_PATH . DIRECTORY_SEPARATOR . 'category/model.php';
	//获取下级所有分类ID
	$category_child_ids = category_model_get_child_ids($category_id);
	$category_ids = "";
	//分类ID通过,链接
	if (empty($category_child_ids)) {
		$category_ids = $category_id;
	} else {
		$category_ids = $category_child_ids . ',' . $category_id;
	}

	// 引入数据库链接操作
	require_once CORE_PATH . 'db.php';
	//sql查询
	$sql = "select count(id) as count from users where category_id in(" . $category_ids . ") and `status` = 1 and `draft` =0   order by id desc ";
	$result_count = 0;
	try
	{
		//创建实力
		$db = Db::getInstance()->connect();
		//查询
		$result = mysqli_query($db, $sql);
		//结果处理
		if ($result) {
			$row = mysqli_fetch_assoc($result);
			if ($row) {
				$result_count = $row['count'];
			}

		} else {
			//SQL报错停止
			die('mysql error' . mysqli_error($db));
		}

	} catch (Exception $e) {
		// 其他异常显示
	}
	//返回
	return $result_count;
}

function user_model_get_all_list_count($category_id = 0, $keyword = '') {
	$where = " 1=1 ";

	//数据安全过滤
	$keyword = trim($keyword);
	//分类
	$category_id = intval($category_id);
	require_once APP_PATH . DIRECTORY_SEPARATOR . 'category/model.php';
	// 引入数据库链接操作
	require_once CORE_PATH . 'db.php';

	require_once APP_PATH . DIRECTORY_SEPARATOR . 'category/model.php';

	if (!empty($category_id)) {
		//获取下级所有分类ID
		$category_child_ids = category_model_get_child_ids($category_id);
		$category_ids = "";
		//分类ID通过,链接
		if (empty($category_child_ids)) {
			$category_ids = $category_id;
		} else {
			$category_ids = $category_child_ids . ',' . $category_id;
		}

		$where .= "and category_id in (" . $category_ids . ") ";
	}

	if (!empty($keyword)) {
		$where .= "and (title like '%" . $keyword . "%' or content like '%" . $keyword . "%')";
	}

	//sql查询
	$sql = "select count(id) as count from users where " . $where;
	$result_count = 0;
	try
	{
		//创建实力
		$db = Db::getInstance()->connect();
		//查询
		$result = mysqli_query($db, $sql);
		//结果处理
		if ($result) {
			$row = mysqli_fetch_assoc($result);
			if ($row) {
				$result_count = $row['count'];
			}

		} else {
			//SQL报错停止
			die('mysql error' . mysqli_error($db));
		}

	} catch (Exception $e) {
		// 其他异常显示
	}
	//返回
	return $result_count;
}
/**
 * 根据分类获取列表
 * @param  integer
 * @param  integer
 * @param  integer
 * @return [type]
 */
function user_model_get_all_list($page = 1, $page_size = 8, $keyword = '') {
	$where = " 1=1 ";
	//数据安全过滤
	//分类
	$category_id = intval($category_id);
	//分页
	$page = intval($page);
	//防止出现负数
	if ($page <= 0) {
		$page = 1;
	}
	//页码转换成数据库limit
	$limit = ($page - 1) * $page_size;
	// 引入数据库链接操作
	require_once CORE_PATH . 'db.php';

	require_once APP_PATH . DIRECTORY_SEPARATOR . 'category/model.php';

	if (!empty($category_id)) {
		//获取下级所有分类ID
		$category_child_ids = category_model_get_child_ids($category_id);
		$category_ids = "";
		//分类ID通过,链接
		if (empty($category_child_ids)) {
			$category_ids = $category_id;
		} else {
			$category_ids = $category_child_ids . ',' . $category_id;
		}

		$where .= "and category_id in (" . $category_ids . ") ";
	}

	if (!empty($keyword)) {
		$where .= "and (title like '%" . $keyword . "%' or content like '%" . $keyword . "%')";
	}
	//sql查询
	$sql = "select * from users where " . $where . "  order by id desc  limit " . $limit . "," . $page_size;
	//结果数组
	$users_array = array();
	try
	{
		//创建实力
		$db = Db::getInstance()->connect();
		//查询
		$result = mysqli_query($db, $sql);
		//结果处理
		if ($result) {
			//循环结果
			while ($row = mysqli_fetch_assoc($result)) {
				//加入结果
				$users_array[] = $row;
			}
		} else {
			//SQL报错停止
			die('mysql error' . mysqli_error($db));
		}

	} catch (Exception $e) {
		// 其他异常显示
	}
	//返回数组
	return $users_array;
}

/**
 * 根据id获取数据
 *
 * @param  string
 * @return [type]
 */
function user_model_get_by_id($id = '') {
	if (empty($id)) {
		return false;
	}
	$id = intval($id);
	// 引入数据库链接操作
	require_once CORE_PATH . 'db.php';
	$sql = "select * from users where `id`=? limit 1";
	$user_data = false;
	try
	{
		$db = Db::getInstance()->connect();
		$stmt = $db->prepare($sql);

		if (!$stmt) {

			return false;
		}
		if (!$stmt->bind_param('i', $id)) {
			$stmt->close();

			return false;
		}
		if (!$stmt->execute()) {

			$stmt->close();

			return false;
		} else {
			//查询成功
			$stmt->store_result();
			$result = $stmt->result_metadata();
			$fields = $result->fetch_fields();
			foreach ($fields as $field) {
				$column[] = &$out[$field->name];
			}
			call_user_func_array(array($stmt, 'bind_result'), $column);
			$res = array();
			while ($stmt->fetch()) {
				$t = array();
				foreach ($out as $key => $val) {
					$t[$key] = $val;
				}
				$res = $t;
			}

			$stmt->close();
			return $res;
		}

	} catch (Exception $e) {
		// TODO
	}
	return $user_data;
}
function user_model_insert_count($id = '', $ip = '', $user_agent = '') {
	if (empty($id)) {
		return false;
	}
	if (empty($ip)) {
		return false;
	}
	// 引入数据库链接操作
	require_once CORE_PATH . 'db.php';
	$id = intval($id);
	$ip = trim($ip);
	$user_agent = fn_safe($user_agent);
	$create_time = date('Y/m/d H:i:s', time());

	$sql = "insert into user_counts(ip,id,user_agent,create_time)values('" . $id . "','" . $ip . "','" . $user_agent . "','" . $create_time . "')";
	try
	{
		$db = Db::getInstance()->connect();
		$result = mysqli_query($db, $sql);
	} catch (Exception $e) {
		// TODO
	}
}

function user_model_insert($username = '', $password = '', $nickname = '', $email = '', $mobile = '') {

	// 引入数据库链接操作
	require_once CORE_PATH . 'db.php';
	$username = trim($username);
	$password = trim($password);
	$nickname = trim($nickname);
	$email = trim($email);
	$mobile = trim($mobile);
	$register_time = date('Y-m-d H:i:s', time());
	//SQL模板
	$sql = "insert into `users` (`username`,`password`,`nickname`,`email`,`mobile`,`register_time`,`register_ip`)values(?,?,?,?,?,?,?)";
	try
	{
		$db = Db::getInstance()->connect();
		// echo ("ERROR: " . mysqli_connect_error());
		$stmt = $db->prepare($sql);

		if (!$stmt) {

			return false;
		}
		$register_ip = get_ip();

		if (!$stmt->bind_param('sssssss', $db_username, $db_password, $db_nickname, $db_email, $db_mobile, $db_register_time, $db_register_ip)) {

			$stmt->close();
			return false;
		}
		$db_username = $username;
		$db_password = $password;
		$db_nickname = $nickname;
		$db_email = $email;
		$db_mobile = $mobile;
		$db_register_time = $register_time;
		$db_register_ip = $register_ip;
		if (!$stmt->execute()) {

			$stmt->close();

			return false;
		} else {
			$stmt->close();

			return true;
		}

	} catch (Exception $e) {
		return false;
	}
}

function user_model_update_by_id($id = 0, $nickname, $email = '', $status = 0) {

	// 引入数据库链接操作
	require_once CORE_PATH . 'db.php';
	$id = intval($id);
	if (empty($id)) {
		return false;
	}

	$title = trim($title);
	$modify_time = date('Y-m-d H:i:s', time());
	$draft = intval($draft);
	$status = intval($status);
	$sql = "update users set category_id=?,title=?,content=?,modify_time=?,draft=?,status=? where id=?";
	try
	{
		$db = Db::getInstance()->connect();
		$stmt = $db->prepare($sql);
		if (!$stmt) {

			$stmt->close();

			return false;
		}

		if (!$stmt->bind_param('isssiis', $category_id, $title, $content, $modify_time, $draft, $status, $id)) {

			$stmt->close();

			return false;
		}

		if (!$stmt->execute()) {

			$stmt->close();

			return false;
		} else {
			$stmt->close();

			//更新HTML
			user_build_page_by_id($id);
			return true;
		}
	} catch (Exception $e) {
		// TODO
		echo $e;
	}
}

function user_model_delete_by_id($id = '') {
	// 引入数据库链接操作
	require_once CORE_PATH . 'db.php';
	$id = intval($id);
	if (empty($id)) {
		return false;
	}
	$user_data = user_model_get_by_id($id);

	//删除数据库记录
	$sql = "delete from users where id=?";
	try
	{
		$db = Db::getInstance()->connect();
		$stmt = $db->prepare($sql);
		if (!$stmt) {

			$stmt->close();

			return false;
		}

		if (!$stmt->bind_param('s', $id)) {

			$stmt->close();

			return false;
		}

		if (!$stmt->execute()) {

			$stmt->close();

			return false;
		} else {
			$stmt->close();

			//删除物理文件
			user_delete_html_by_id($user_data);
			return true;
		}
	} catch (Exception $e) {
		// TODO
		echo $e;
		return false;
	}
}

function user_model_update_password_by_id($id = 0, $old_password = '', $new_password = '') {

	// 引入数据库链接操作
	require_once CORE_PATH . 'db.php';
	$id = intval($id);
	if (empty($id)) {
		return false;
	}

	$old_password = trim($old_password);
	$modify_time = date('Y-m-d H:i:s', time());
	$modify_ip = get_ip();
	$login_status = user_model_login_by_id($id, $old_password);

	if ($login_status) {
		$sql = "update users set password=?,modify_time=?,modify_ip=? where id=?";
		try
		{
			$db = Db::getInstance()->connect();
			$stmt = $db->prepare($sql);
			if (!$stmt) {
				$stmt->close();
				die('mysql error=' . mysqli_error($db));
				return false;
			}
			require_once APP_PATH . '/user/helper.php';
			//密码算法
			$encrypt_password = get_user_encrypt_password($new_password);

			if (!$stmt->bind_param('sssi', $encrypt_password, $modify_time, $modify_ip, $id)) {
				$stmt->close();
				die('mysql error=' . mysqli_error($db));
				return false;
			}

			if (!$stmt->execute()) {
				$stmt->close();
				die('mysql error=' . mysqli_error($db));
				return false;
			} else {
				$stmt->close();

				return true;
			}
		} catch (Exception $e) {

			// TODO
			return false;
		}
	} else {
		echo "login failed.";
		return false;
	}

}
/**
 * 按ID登录
 * @param  [type]
 * @param  [type]
 * @return [type]
 */
function user_model_login_by_id($id = 0, $password = '') {

	// 引入数据库链接操作
	require_once CORE_PATH . 'db.php';
	$id = intval($id);
	if (empty($id)) {
		return false;
	}
	$sql = "select password from users where id=?";
	try
	{
		$db = Db::getInstance()->connect();
		$stmt = $db->prepare($sql);
		if (!$stmt) {
			$stmt->close();

			return false;
		}

		if (!$stmt->bind_param('i', $id)) {
			$stmt->close();

			return false;
		}

		if (!$stmt->execute()) {
			$stmt->close();

			return false;
		} else {
			$login_status = false;
			//查询成功
			$stmt->store_result();
			$stmt->bind_result($db_password);

			if ($stmt->fetch()) {
				require_once APP_PATH . '/user/helper.php';
				$encrypt_password = get_user_encrypt_password($password);
				if ($db_password == $encrypt_password) {
					$login_status = true;
				} else {
					$login_status = false;
				}
			}

			$stmt->close();

			return $login_status;
		}
	} catch (Exception $e) {
		// TODO
		return false;
	}
}

/**
 * 按ID登录
 * @param  [type]
 * @param  [type]
 * @return [type]
 */
function user_model_login_by_username($username = '', $password = '') {

	// 引入数据库链接操作
	require_once CORE_PATH . 'db.php';
	$username = trim($username);
	if (empty($username)) {
		return false;
	}
	$sql = "select id,password from users where username=? limit 1";
	try
	{
		$db = Db::getInstance()->connect();
		$stmt = $db->prepare($sql);
		if (!$stmt) {

			return false;
		}

		if (!$stmt->bind_param('s', $username)) {
			$stmt->close();

			return false;
		}

		if (!$stmt->execute()) {
			$stmt->close();

			return false;
		} else {
			$login_status = false;
			//查询成功
			$stmt->store_result();
			$stmt->bind_result($uid, $db_password);

			if ($stmt->fetch()) {
				require_once APP_PATH . '/user/helper.php';
				$encrypt_password = get_user_encrypt_password($password);
				if ($db_password == $encrypt_password) {

					$stmt->close();
					return $uid;
				} else {
					$stmt->close();
					return false;
				}
			}
		}
	} catch (Exception $e) {
		// TODO
		return false;
	}
}
/**
 * 用户登录函数
 * @param  string
 * @param  string
 * @return [type]
 */
function user_model_login($account = '', $password = '') {
	$ret = user_model_login_by_username($account, $password);
	if ($ret) {
		$user_data = user_model_get_by_id($ret);
		return $user_data;
	} else {
		return false;
	}
}
/**
 * 检查用户是否已经被注册
 * @param  string
 * @return [type]
 */
function user_model_check_username($username = '') {

	// 引入数据库链接操作
	require_once CORE_PATH . 'db.php';
	$username = trim($username);
	if (empty($username)) {
		return false;
	}
	$sql = "select id from users where username=? limit 1";
	try
	{
		$db = Db::getInstance()->connect();
		$stmt = $db->prepare($sql);
		if (!$stmt) {

			return false;
		}

		if (!$stmt->bind_param('s', $username)) {
			$stmt->close();

			return false;
		}

		if (!$stmt->execute()) {
			$stmt->close();

			return false;
		} else {
			//查询成功
			$stmt->store_result();
			$stmt->bind_result($uid);
			$check_status = false;
			if ($stmt->fetch()) {
				$check_status = true;
			}

			$stmt->close();

			return $check_status;
		}
	} catch (Exception $e) {
		// TODO
		return false;
	}
}
/**
 * 用户注册函数
 * @param  string
 * @param  string
 * @return [type]
 */
function user_model_register($account = '', $password = '') {
	$ret = user_model_check_username($account);
	if ($ret) {
		//用户已经存在了
		return false;
	} else {
		require_once APP_PATH . '/user/helper.php';
		$password = get_user_encrypt_password($password);
		//注册流程
		return user_model_insert($account, $password);
	}
}